package package1;
	/**
	 * convert between decimal and binary 
	 * @author Alvin
	 *
	 */
public class TestForBinaryAndDecimalConvert {
	public static void main(String[] args) throws Exception {
		int decimal = 11;
		int binary = 11110111;
		decimalToBinary(decimal);
		binaryToDecimal1(binary);
		binaryToDecimal2(binary);
		zhengzebiaodashi();
	}
	
	private static void binaryToDecimal2(int binary) {
		binaryToDecimal2(binary,0,0);
	}

	private static void binaryToDecimal2(int binary,int pow,int num) {
		if(binary>0){
			int a = binary%10;
			int b = binary/10;
			num += Math.pow(2, pow)*a;
			binaryToDecimal2(b,pow+1,num);
		}else System.err.println(num);
	}

	private static void zhengzebiaodashi() {
		String ptn = "[^0|1]+";
		String str = "2";
		if(str.matches(ptn)) System.err.println(true);
		else System.err.println(false);
	}

	private static void binaryToDecimal1(int binary) throws Exception {
		String str = binary+"";
		String reg = "[0|1]+";
		if(!str.matches(reg)) throw new Exception(binary+" is not a valid binary");
		int decimal = 0;
		for(int i=0;i<str.length();i++){
			char ch = str.charAt(i);
			if(ch==49)//'1' == 49
			{
				System.err.println("i:1");
				int temp = (int) Math.pow(2, str.length()-i-1);
				decimal += temp;
			}
			else System.err.println("i:0");
		}
		System.err.println(decimal);
	}

	private static void decimalToBinary(int decimal) {
		decimalToBinary(decimal,"");
	}

	private static void decimalToBinary(int decimal,String right) {
		if(decimal>0){
			String left = decimal%2+"";
			left = left+right;
			decimalToBinary(decimal/2,left);
		}else System.err.println(right);
	}
}
